<template>
    <div class="app-container">
      <div v-loading="loading" class="filter-container" style=" display: flex;">
        <div style="width: 60%; padding-right: 1px;">
          <el-form ref="dataForm" :model="form" label-width="150px" :rules="rules" style="width:100%;margin-top:20px">
            <el-form-item label="档案模板名称：" prop="template_name">
              <el-col :span="12">
                <el-input v-model="form.template_name" placeholder="请输入模版名称呢过" style="width: 100%;" />
              </el-col>
            </el-form-item>
  
            <!-- <el-form-item label="优先级：" prop="priority">
              <el-col :span="12">
                <el-input-number v-model="form.priority" :min="1" :max="1000" placeholder="请输入优先级" />
              </el-col>
            </el-form-item> -->
  
            <el-form-item label="判定特征：" prop="identifying_features">
              <div>
                <div v-for="(item, index) in list" :key="item.key" class="row">
                  <div v-if="index!==0" class="huo">
                    或
                  </div>
                  <el-col class="flex">
                    <div v-for="(valueItem, indexHuo) in item.value" :key="valueItem.key" class="flex">
                      <div v-if="indexHuo!==0" style="margin: auto 10px;">
                        且
                      </div>
                      <el-select v-model="valueItem.titleOrContent" style="width:100px">
                        <!-- <el-option label="标题" value="1" /> -->
                        <el-option label="内容" value="content" />
                        <el-option label="题名" value="tm" />
  
                        <el-option label="文件编号" value="wjbh" />
                        <el-option label="档号" value="dh" />
                        <el-option label="全宗号" value="gzh" />
                        <el-option label="类别号" value="lbh" />
                        <el-option label="案卷号" value="ajh" />
                        <el-option label="全文标识" value="gwbs" />
                        <el-option label="责任者" value="zrz" />
                        <el-option label="主题词" value="ztc" />
                      </el-select>
                      <el-input v-model="valueItem.value" style="width: 150px;margin-left: 10px; " />
                      <div>
                        <el-button type="danger" style="margin-left: 5px;" @click.prevent="remove(index,indexHuo)">
                          删除
                        </el-button>
                      </div>
                    </div>
  
                    <el-button type="primary" style="margin-left: 15px;margin-bottom: 15px;" @click.prevent="add(index)">
                      增加且
                    </el-button>
                  </el-col>
                  <div>
                    <el-button type="danger" @click.prevent="removeRow(index)">
                      删除或
                    </el-button>
                  </div>
                </div>
  
                <el-button type="primary" style=" margin-top: 10px;" @click.prevent="addRow()">
                  增加或
                </el-button>
              </div>
            </el-form-item>
  
            <el-form-item label="提示词" prop="status">
              <el-col :span="20">
                <el-input v-model="form.persondesc" type="textarea" :autosize="{ minRows: 12, maxRows: 60}" />
              </el-col>
            </el-form-item>
  
            <el-form-item label="启用状态：" prop="status">
              <el-col :span="15">
                <el-switch v-model="form.status" />
              </el-col>
            </el-form-item>
  
            <!-- <el-form-item label="抽取方式：">
              <el-col :span="15">
                <el-radio-group v-model="form.mode">
                  <el-radio label="1">
                    霍夫算法
                  </el-radio>
                  <el-radio label="2">
                    大模型抽取
                  </el-radio>
                  <el-radio label="3">
                    不抽取
                  </el-radio>
                </el-radio-group>
              </el-col>
            </el-form-item> -->
  
            <el-form-item>
              <el-button type="info" @click="$router.push('/template/promptwordmanagement')">
                返回
              </el-button>
              <!-- <el-button :loading="isDisabled" type="primary" @click="submit">
                抽取
              </el-button> -->
              <el-button type="warning" @click="addtemp">
                保存
              </el-button>
              <el-button type="success" :loading="testLoading" @click="submitRTest">
                测试抽取
              </el-button>
            </el-form-item>
          </el-form>
        </div>
  
        <div style="padding-left: 2px; width: 40%;">
          <div style="display:flex;align-items: center;justify-content: center;flex-direction: column;">
            <div style="margin-top: 20px;  ">
              <span style="font-size: 12px;">文章案例ID</span> <el-input v-model="form.article_id"
                style="width: 150px; margin-left: 10px;" placeholder="" clearable />
              <el-button style="margin-left: 10px;" @click="fullTextPreview">
                全文预览
              </el-button>
              <el-button type="success" @click="validate">
                验证
              </el-button>
            </div>
  
            <div style="margin-top: 20px;">
              <span>{{ title }}</span>
            </div>
  
            <el-divider />
            <div>
              <div style="font-size: 12px;white-space:pre-wrap" v-html="htmlContent" />
            </div>
  
            <div v-if="batch_code!=''"
              style="display: flex; flex-direction: row-reverse;justify-content: flex-start;width: 100%; font-size: 12px;" />
          </div>
        </div>
      </div>
      <el-dialog
        title="测试结果"
        :visible.sync="dialogVisible"
        :close-on-click-modal="false"
        :append-to-body="true"
        width="60%"
        center
        class="test-result-dialog">
        <div class="dialog-content">
          <pre style="margin: 0; font-family: Monaco, monospace; font-size: 14px; line-height: 1.5; background-color: #f8f8f8; padding: 15px; border-radius: 4px; overflow: auto;">{{ jsonResult }}</pre>
        </div>
        <span slot="footer" class="dialog-footer">
          <el-button @click="dialogVisible = false">关闭</el-button>
        </span>
      </el-dialog>
    </div>
  </template>
  
  <script>
  
  import { api } from '@/api/template'
  import { artApi } from '@/api/art'
  import { modelextractionApi } from '@/api/modelextraction'
  import { zstpobtainqueueApi } from '@/api/zstpobtainqueue'
  
  export default {
    components: {},
    data() {
      return {
        loading: false,
        testLoading: false,
        saveStatus: false,
        batch_code: "",
        htmlContent: "",
        title: "",
        content: '',
        dialogVisible: false,
        jsonResult: '',
  
        isDisabled: false,
        list: [
          {
            key: Date.now(),
            value: [
              { titleOrContent: "", value: "", key: Date.now(), },
            ]
          }
        ],
        form: {
          id: "",
          template_name: '',
          priority: '',
          status: true,
          mode: "2",
          identifying_features: [],
          article_id: "",
          skip_template_notes: "",
          ollama_url: ''
        },
        rules: {
          template_name: [
            { required: true, message: '请输入模板名字', trigger: 'blur' }
          ],
          priority: [
            { required: true, message: '请输入优先级', trigger: 'blur' }
          ],
  
  
        }
  
      }
    },
    mounted() {
  
      this.form.id = this.$route.query.id
  
      this.form.article_id = this.$route.query.article_id
  
      if (this.form.id != null) {
        this.getDetail()
      }
  
      if (this.form.article_id != null) {
        this.fullTextPreview()
      }
  
  
  
    },
    methods: {
  
      async validate() {
  
  
        const url = 'validateTemplate'
  
        this.form.identifying_features = this.list
  
        var res = await artApi(url, this.form)
        if (res.code == 200) {
          this.$message.success(res.message)
        }
  
  
      },
  
  
      async getDetail() {
  
        const url = 'getTemplateById'
        var res = await api(url, { id: this.form.id })
        if (res.code == 200) {
          this.form = res.data;
  
          if (res.data.status == 1) {
            this.form.status = true
          } else {
            this.form.status = false
          }
          this.list = res.data.identifying_features
  
  
  
        }
  
      },
  
      removeRow(index) {
        let mun = this.list.length
  
        if (mun <= 1) {
          this.$message.error('至少保留一个')
          return
        }
  
        this.list.splice(index, 1)
  
      },
  
      addRow() {
  
  
        let row = {
          key: Date.now(),
          value: [
            { titleOrContent: "", value: "" },
          ]
        };
  
        this.list.push(row)
  
  
      },
  
      async fullTextPreview() {
        const url = 'getArticleByid'
        var res = await artApi(url, { id: this.form.article_id })
        if (res.code == 200) {
          // this.htmlContent = res.data.content.replace(/\n\n/g, '</p><p>').replace(/\n/g, '<br>');
          this.htmlContent = res.data.content;
          this.title = res.data.title;
          this.batch_code = res.data.batch_code
        }
  
      },
  
      add(index) {
  
        this.list[index]['value'].push({
          value: '',
          titleOrContent: '',
          key: Date.now()
        })
  
      },
  
      remove(index, indexHuo) {
  
        console.log(index, indexHuo)
  
        let mun = this.list[index]['value'].length
  
        if (mun <= 1) {
          this.$message.error('至少保留一个')
          return
        }
  
        this.list[index]['value'].splice(indexHuo, 1)
  
      },
  
      saveNew() {
  
        this.$refs.dataForm.validate(async valid => {
          if (valid) {
            this.isDisabled = true
            let params = this.form
  
            console.log(this.form)
  
            if (this.form.status) {
              params.status = 1;
            } else {
              params.status = 0;
            }
  
            params.identifying_features = this.list;
  
  
  
            const url = 'saveOrUptTemplateFind'
  
            this.saveStatus = true
  
            var res = await api(url, params)
            this.saveStatus = false
  
            if (res.code == 200) {
              // this.$message.success('操作成功！')
  
              this.$message.success(res.message)
  
              this.form.article_id = res.data
              setTimeout(() => {
                window.location.href = '/template/templateSave?article_id=' + this.form.article_id;
              }, 1500);
  
  
            }
  
          }
        })
  
  
      },
  

  
      async addtemp() {
  
  
        this.$refs.dataForm.validate(async valid => {
          if (valid) {
            // this.isDisabled = true
            let params = this.form
  
            console.log(this.form)
  
            if (this.form.status == true) {
              params.status = 1;
            } else {
              params.status = 0;
            }
  
            params.identifying_features = this.list;
  
  
  
            const url = 'saveTemplate'
            var res = await modelextractionApi(url, params)
            if (res.code == 200) {
              this.$message.success('操作成功！')
              this.$router.push('/template/promptwordmanagement')
            }
  
            // this.loading = false
          }
        })
  
      },
  
  
  
      async submitRTest() {
        try {
          this.testLoading = true
          
          const valid = await this.$refs.dataForm.validate()
          if (valid) {
            const params = {
              ...this.form,
              status: this.form.status ? 1 : 0,
              identifying_features: this.list
            }
            
            const response = await zstpobtainqueueApi('saveOrUptTempTest', params)
            if (response.code === 200) {
              this.jsonResult = JSON.stringify(response, null, 2)
              this.dialogVisible = true
            } else {
              this.$message.error(response.message || '操作失败')
            }
          }
        } catch (error) {
          console.error('测试抽取失败:', error)
          this.$message.error('测试抽取失败：' + (error.message || '未知错误'))
        } finally {
          this.testLoading = false
        }
      },
  
      async testConnection() {
        try {
          const loading = this.$loading({
            lock: true,
            text: '正在测试连接...',
            spinner: 'el-icon-loading',
            background: 'rgba(0, 0, 0, 0.7)'
          })
          
          const response = await api('testOllamaConnection', {
            url: this.form.ollama_url
          })
          
          loading.close()
          
          if (response.code === 200) {
            this.$notify({
              title: '成功',
              message: 'Ollama服务连接成功',
              type: 'success',
              duration: 2000
            })
          } else {
            this.$notify({
              title: '错误',
              message: response.message || 'Ollama服务连接失败',
              type: 'error',
              duration: 2000
            })
          }
        } catch (error) {
          this.$notify({
            title: '错误',
            message: '测试连接时发生错误：' + (error.message || '未知错误'),
            type: 'error',
            duration: 2000
          })
        }
      }
  
    }
  }
  </script>
  
  <style scoped>
  .huo {
    clear: both;
    margin-top: 15px;
    margin-bottom: 10px;
  }
  
  .flex {
    display: flex;
    flex-wrap: wrap;
    margin-bottom: 10px;
  }
  .row {
    display: flex;
    flex-direction: column;
  }
  
  .el-divider--horizontal {
    width: 80%;
  }
  
  .filter-container {
    position: relative;
    align-items: baseline;
  }
  
  .filter-container::after {
    content: "";
    position: absolute;
    top: 10%; /* 上边距，可以根据需要调整 */
    bottom: 10%; /* 下边距，可以根据需要调整 */
    left: 58%; /* 调整为左边div的宽度百分比加上它的padding */
    width: 2px; /* 分隔线宽度 */
    background-image: linear-gradient(
      to bottom,
      rgba(0, 0, 0, 0) 0%,
      rgba(0, 0, 0, 0) 49%,
      rgba(0, 0, 0, 1) 50%,
      rgba(0, 0, 0, 0) 100%
    );
    background-size: 2px 4px; /* 控制虚线的宽度和间隔 */
  }
  
  .test-result-dialog {
    /deep/ .el-dialog__header {
      padding: 20px;
      border-bottom: 1px solid #e8e8e8;
    }

    /deep/ .el-dialog__body {
      padding: 20px;
    }

    /deep/ .el-dialog__footer {
      padding: 20px;
      border-top: 1px solid #e8e8e8;
      text-align: right;
    }

    .dialog-content {
      max-height: 60vh;
      overflow: auto;
    }
  }
  </style>
  